<template>
  <a-form
    ref="formRef"
    :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }"
    :model="state.printFrom"
    :rules="state.rules"
  >
    <a-row>
      <a-col :span="6">
        <a-form-item label="客户信息" name="customerCode">
          <a-select v-model:value="state.printFrom.customerCode" :allowClear="true" :style="`width: 100%`" placeholder="请选择归属客户">
            <a-select-option v-for="item in state.customerData" :key="item.customerCode" :value="item.customerCode">
              {{ item.customerAbbreviation }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="供应商信息" name="supplierCode">
          <a-select v-model:value="state.printFrom.supplierCode" :allowClear="true" :style="`width: 100%`" placeholder="请选择归属供应商">
            <a-select-option v-for="item in state.supplierData" :key="item.supplierCode" :value="item.supplierCode">
              {{ item.supplierAbbreviation }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="品牌信息" name="brand">
          <a-input v-model:value="state.printFrom.brand" placeholder="品牌信息" style="width: 100%" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="18">
        <a-form-item label="原厂条码" name="oriBarcode">
          <a-input v-model:value="state.printFrom.oriBarcode" placeholder="原厂条码" style="width: 100%" @press-enter="parseBarcode" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-button
          v-privilege="'customerInfo:setParseOriFacBarcode'"
          style="margin-left: 10px; width: 100px"
          type="primary"
          @click="openParseOriBarcode"
          >设置条码格式
        </a-button>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <a-form-item label="物料信息" name="materialCode">
          <TableSelect
            v-model:modelValue="state.printFrom.materialCode"
            :columns="[
              { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
              { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
              { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
              { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
            ]"
            :options="materialData"
            :placeholder="'输入物料编号/名称/规格'"
            @search="handleMaterialSearch"
            @select="handleMaterialSelect"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="物料描述" name="materialDesc">
          <a-input v-model:value="state.printFrom.materialDesc" placeholder="物料描述" style="width: 100%" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <a-form-item label="批次号" name="batchNo">
          <a-input v-model:value="state.printFrom.batchNo" placeholder="批次号" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="参考储位" name="defaultStorageLocation">
          <a-input v-model:value="state.printFrom.defaultStorageLocation" placeholder="参考储位" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="D/C" name="dc">
          <a-input v-model:value="state.printFrom.dc" placeholder="D/C" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-button style="margin-left: 10px; width: 100px" type="primary" @click="setPrintTemp">设置打印模板</a-button>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <a-form-item label="包装数" name="packageNum">
          <a-input-number v-model:value="state.printFrom.packageNum" :min="1" placeholder="包装数" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="打印数量" name="printCount">
          <a-input-number v-model:value="state.printFrom.printCount" :min="1" placeholder="盘数" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="有效天数" name="validDay">
          <a-input-number v-model:value="state.printFrom.validDay" :min="1" placeholder="包装数" style="width: 100%" />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-button v-privilege="'materialBarcode:generate'" style="margin-left: 10px; width: 100px" type="primary" @click="printTag()"
          >直接打印
        </a-button>
      </a-col>
    </a-row>
  </a-form>
  <Print ref="printRef" />
  <ParseOriBarcode ref="parseOriBarcodeRef" />
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import { supplierInfoApi } from '/@/api/business/basic/supplier/supplier-info-api.js';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';
  import { materialBarcodeApi } from '/@/api/business/basic/material/material-barcode-api.js';
  import { printTemplateApi } from '/@/api/business/basic/print/print-template-api.js';
  import { MATERIAL_TAG_ID } from '/@/constants/business/basic/print-template-const.js';
  import Print from '/@/components/print/index.vue';
  import ParseOriBarcode from './parseOriBarcode.vue';
  import { defaultElementTypeProvider, hiprint } from 'vue-plugin-hiprint';
  import { message } from 'ant-design-vue';
  import TableSelect from '/src/components/TableSelect/index.vue';

  const formRef = ref();
  const printRef = ref();
  const parseOriBarcodeRef = ref();

  const emit = defineEmits(['reloadBarcodeList']);

  const materialData = ref();

  const handleMaterialSelect = (value) => {
    state.printFrom.materialCode = value.record.materialCode;
    state.printFrom.materialDesc = value.record.materialDesc;
  };

  const handleMaterialSearch = (searchValue) => {
    let param = {
      keywords: searchValue,
      belongCustomer: state.printFrom.customerCode,
      materialProperty: 'ROW',
    };
    materialInfoApi.searchTop10(param).then((res) => {
      materialData.value = res.data;
    });
  };

  const state = reactive({
    printFrom: {
      customerCode: null,
      supplierCode: null,
      brand: '',
      oriBarcode: '',
      materialCode: '',
      materialDesc: '',
      packageNum: '',
      defaultStorageLocation: '',
      batchNo: '',
      validDay: 365,
      dc: '',
      printCount: '1',
    },
    rules: {
      materialCode: [{ required: true, message: '物料编号不能为空' }],
      batchNo: [{ required: true, message: '批次号不能为空' }],
      packageNum: [{ required: true, message: '包装数不能为空' }],
      printCount: [{ required: true, message: '打印数量不能为空' }],
    },
    customerData: [],
    supplierData: [],
  });

  function customerAll() {
    customerInfoApi.customerAll().then((res) => {
      state.customerData = res.data;
    });
  }

  function supplierAll() {
    supplierInfoApi.all().then((res) => {
      state.supplierData = res.data;
    });
  }

  function setPrintTemp() {
    printRef.value.show();
  }

  //const {proxy} = getCurrentInstance();
  async function printTag() {
    try {
      await formRef.value.validateFields();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
      return;
    }
    let printData;
    await materialBarcodeApi.generate(state.printFrom).then((res) => {
      printData = res.data;
    });

    // 添加调试信息
    console.log('表单数据:', state.printFrom);
    console.log('打印数据:', printData[0]);
    await printByData(printData);
  }

  function reprint(data) {
    printByData(data);
  }

  async function printByData(printData) {
    try {
      let templateJsonStr;
      await printTemplateApi.getPrintTemplate(MATERIAL_TAG_ID).then((res) => {
        templateJsonStr = res.data.templateJson;
      });
      let templateJson = JSON.parse(templateJsonStr);
      // 创建PrintTemplate对象
      let template = new hiprint.PrintTemplate({
        template: templateJson,
      });
      // 使用模板对象的print方法进行打印
      if (hiprint.hiwebSocket && hiprint.hiwebSocket.opened) {
        // 客户端打印
        template.print2(printData);
        emit('reloadBarcodeList');
        message.success('打印任务已发送到客户端');
      } else {
        // 浏览器打印
        template.print(printData, { leftOffset: -1, topOffset: -1 });
        message.success('已调用浏览器打印');
        emit('reloadBarcodeList');
      }
    } catch (error) {
      console.error('打印失败:', error);
      message.error('打印失败: ' + error.message);
    }
  }

  function openParseOriBarcode() {
    if (state.printFrom.customerCode === '') {
      message.error('请先选择客户信息在设置条码格式!');
      return;
    }
    parseOriBarcodeRef.value.show(state.printFrom.customerCode);
  }

  function parseBarcode() {
    if (state.printFrom.customerCode === '') {
      message.error('请先选择客户信息!');
      return;
    }
    if (state.printFrom.oriBarcode === '') {
      message.error('请输入原厂条码信息!');
      return;
    }
    let param = {
      customerCode: state.printFrom.customerCode,
      oriBarcode: state.printFrom.oriBarcode,
    };
    customerInfoApi.parseOriFacBarcode(param).then((res) => {
      state.printFrom.oriBarcode = '';
      for (let key in state.printFrom) {
        if (Object.prototype.hasOwnProperty.call(res.data, key)) {
          console.log(key, res.data[key]);
          state.printFrom[key] = res.data[key];
        }
      }
    });
  }

  // 初始化hiprint
  onMounted(() => {
    try {
      hiprint.init({
        providers: [defaultElementTypeProvider()],
      });
      console.log('hiprint 初始化成功');
    } catch (error) {
      console.error('hiprint 初始化失败:', error);
    }
    onShow();
  });

  function onShow() {
    customerAll();
    supplierAll();
  }

  defineExpose({
    reprint,
  });
</script>
<style scoped lang="less"></style>
